<?php
/**
 * Copyright (c) 2010, Slawomir Mazur <mazursllawek@gmail.com>
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions 
 * are met:
 * 
 * o Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * o Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * o Neither the name of the Softisland nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * Enter description here...
 *
 * @package     Admin
 * @subpackage  Admin_Attribute
 * @copyright   Slawomir Mazur (c) 2010 (http://www.zend.com/zce.php?c=ZEND011643)
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @author      Slawomir Mazur <mazursllawek@gmail.com>
 */

class Admin_AttributeController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$this->view->collection = Gp_App::getModel('system/attribute')->getCollection();
	}
	
	public function addAction()
	{		
		$this->view->form = $this->_getForm();
	}
	
	public function editAction()
	{
		$form = $this->_getForm();
    	
    	$form->addElement($this->_getColumIdField(
    			(int) $this->getRequest()->getParam('id', null)
    		)
    	);
    	
    	$form->getElement('delete')->setAttrib('hiddenElement', false);
    	$form->getElement('code')->setAttrib('readonly', 'readonly');
    	
    	$data = $this->_getAttributeById()->toArray();
    	
    	$form->populate($data);
    	
    	$this->view->form = $form;
		
		$this->render('add');
	}
	
	public function editPostAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		
		if (!$this->getRequest()->isPost() || 
    			!$this->getRequest()->getParam('attribute', false)) { 
    		
    		$this->_redirect('admin/attribute/add');
    	}
    	
    	$form = $this->_getForm();
    	$data = $this->getRequest()->getParam('attribute', array());
    	
    	if ($form->isValid($data)) {
    		try {
	    		$id = (int) @$data['attribute_id'];
				$model = Gp_App::getModel('system/attribute');
				
	    		if (!empty($id)) {
	    			$attribute = $this->_getAttributeById(false, $id);
	    		} else {	
		    		if ($model->findAttributeByCode($data['code'], $id)) {
		    			throw new Exception('Attribute with the same name already exists!');
		    		}
	    			
		    		// check whether column exists
		    		if ($model->checkWhetherAttributeColumnExists($data['code'])) {
		    			throw new Exception('Attribute Column with the same name already exists!');
		    		}
		    		
		    		// append column
		    		Gp_App::getModel('system/table')->createColumn($data['code'], $data['type'], $data['typesize']);
		    		
	    			$attribute = $model->createRow();
	    			
	    			// save code, type and type size and create table only once
	    			$attribute->code = $data['code'];
	    			$attribute->type = $data['type'];
					$attribute->typesize = is_numeric($data['typesize'])? $data['typesize'] : 0;
	    		}
				$attribute->name = $data['name'];				
				$attribute->searchable = (@$data['searchable'])? 1 : 0;
				$attribute->position = (int) $data['position'];
	    		$attribute->save();
	    		
	    		// clear stored attributes cache
	    		foreach (Gp_Cache_Manager::getFileCacheObject()
	    						->getIdsMatchingTags(array(System_Model_Attribute::CACHE_TAGS)) as $id) {
					
	    			Gp_Cache_Manager::getFileCacheObject()->remove($id);
				}
	    		
    		} catch (Exception $e) {
    			$this->_helper->getHelper(Gp_View_Helper_Messenger::ADMIN_MESSENGER)
    					->addError($e->getMessage());
    			$this->_redirect('admin/attribute/add');
    		}
    		$this->_helper->getHelper(Gp_View_Helper_Messenger::ADMIN_MESSENGER)
    				->addSuccess('Attribute was added successfully');
    		$this->_redirect('admin/attribute/edit/id/' . $attribute->attribute_id);
    	} else {
    		$allMessages = (array) $form->getMessages('attribute', true);
    		foreach ($allMessages as $filed => $messages) {
    			if (is_array($messages) && (count($messages) > 0)) {
    				foreach ($messages as $message) {
    					$this->_helper->getHelper(Gp_View_Helper_Messenger::ADMIN_MESSENGER)
    							->addError($message);
    				}
    			}
    		}
    		
    		$this->_redirect('admin/attribute/add');
    	}
    	return;
	}
	
	public function deleteAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		
		$params = $this->getRequest()->getParam('attribute', null);

    	try {
    		$attribute = $this->_getAttributeById(false, (int) $params['attribute_id']);
    		$columnName = $attribute->code;
			$attribute->delete();
			
    		// delete column
		    Gp_App::getModel('system/table')->dropColumn($columnName);
    		
	    	// clear stored attributes cache
    		foreach (Gp_Cache_Manager::getFileCacheObject()
    						->getIdsMatchingTags(array(System_Model_Attribute::CACHE_TAGS)) as $id) {
				
    			Gp_Cache_Manager::getFileCacheObject()->remove($id);
			}
		    
    		$this->_helper->getHelper(Gp_View_Helper_Messenger::ADMIN_MESSENGER)
    				->addSuccess('Attribute was deleted successfully');
    	} catch (Exception $e) {
    		$this->_helper->getHelper(Gp_View_Helper_Messenger::ADMIN_MESSENGER)
    				->addError($e->getMessage());
    	}

    	$this->_redirect('admin/attribute');
	}
	
 	protected function _getAttributeById($fromRequest = true, $id = null)
    {
    	if ($fromRequest) {
    		$id = (int) $this->getRequest()->getParam('id', null);
    	}
    	return Gp_App::getModel('system/attribute')->find($id)->current();
    }
    
	protected function _getColumIdField($id)
    {
    	$attributeId = new Zend_Form_Element_Hidden('attribute_id');
        $attributeId->setAttrib('value', $id);
       	return $attributeId;
    }
    
	protected function _getForm()
    {
    	$form = new Gp_Form();
		$form->setAction($this->view->baseUrl('admin/attribute/edit-post'))
			 ->setMethod('post')
			 ->setAttrib('id', 'attribute')
			 ->setElementsBelongTo('attribute')
			 ->setButtonsToReset(array('submit', 'cancel', 'delete'));
    	
        $name = new Zend_Form_Element_Text('name');
        $name->setLabel('Name')
        	   ->setAttrib('class', 'required input-text')
               ->setRequired(true);

		$code = new Zend_Form_Element_Text('code');
        $code->setLabel('Attribute code')
        	   ->setAttrib('class', 'required input-text')
               ->setRequired(true);

        $type = new Zend_Form_Element_Select('type');
        $type->setLabel('Attribute type')
        	   ->setAttrib('class', 'required small-select')
        	   ->setMultiOptions(
        	   		array('' => '...choose type', 
        	   			  'yes/no' => 'yes/no',
        	   			  'char' => 'char', 'varchar' => 'varchar', 'text' => 'text', 
        	   			  'tinyint' => 'tinyint', 'smallint' => 'smallint', 'int' => 'int'
        	   		))
               ->setRequired(true);

        $typeSize = new Zend_Form_Element_Text('type-size');
        $typeSize->removeDecorator('label')
        	   ->setAttrib('class', 'required input-text short-text')
               ->setRequired(true);
               
        $searchable = new Zend_Form_Element_Checkbox('searchable');
		$searchable->setLabel('Use in search by');

		$position = new Zend_Form_Element_Text('position');
		$position->setLabel('Position')
			   ->setAttrib('class', 'required input-text')
			   ->addValidator(new Zend_Validate_Int(), true)
			   ->setValue(0)
			   ->setRequired(true);
               
        $submit = new Zend_Form_Element_Button('submit');
        $submit->setAttrib('class', 'action')
        		->setAttrib('type', 'submit');
        
        $cancel = new Zend_Form_Element_Button('cancel');
        $cancel->setAttrib('class', 'action');
        
        $delete = new Zend_Form_Element_Button('delete');
        $delete->setAttrib('hiddenElement', true)
        		->setAttrib('type', 'submit');
        
        $form->addElements(array($name, $code, $type, $typeSize, $position, $searchable, $submit, $cancel, $delete));
        
        return $form;
    }
}